import { createApp } from "vue";

import Cookies from "js-cookie";
// import locale from "element-plus/lib/locale/lang/zh-cn"; // 中文语言
import "tailwindcss/tailwind.css";
import ElementPlus from "element-plus";
import VXETablePluginElement from 'vxe-table-plugin-element'
// import "element-plus/dist/index.css";
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import VXETable from "vxe-table";
import 'element-plus/dist/index.css'
import "vxe-table/lib/style.css";
import "@/assets/styles/index.scss"; // global css
import "@/assets/iconfont/index.css";

import App from "./App";
import store from "./store";
import router from "./router";
// svg图标
import "virtual:svg-icons-register";
import SvgIcon from "@/components/SvgIcon";
// 全局组件
import Public from "@/componentsPublic";
import confirm from "@/plugins/confirm.jsx";
//挂在指令
import plugins from './plugins' // plugins
import directive from "./directive/index.js";
import "@/plugins/vxe-table.js";    //暂时使用

import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";
import { name as packageName } from "../package.json";

// 子应用修改项
import pinia from "@/store/index";
import keepAliveStore from "@/store/modules/keepalive";
const keepeStore = keepAliveStore(pinia);
import action from "@/utils/action.js";
import { routes } from "@/router/index";
//hiPrint
import {hiPrintPlugin} from 'vue-plugin-hiprint'
import { initMatomo } from '@/utils/initMatomo'
let app;
function render(props) {
  app = createApp(App);
  initMatomo(app)
  const { container, $parentRouter, routerEvent } = props;
  // 主应用全局数据
  app.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
  app.config.globalProperties.$setGlobalState = props.setGlobalState;
  app.config.globalProperties.confirm = confirm;
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
  }
  VXETable.setup({
    tooltipConfig: {
      enterDelay: 0,
      leaveDelay: 0,
    }
  })

  app.use(router);
  app.use(store);
  app.use(VXETable);
  VXETable.use(VXETablePluginElement)
  app.use(Public);
  app.component("svg-icon", SvgIcon);
  app.use(directive)
  app.use(plugins)
  // 使用element-plus 并且设置全局的大小
  app.use(ElementPlus, {
    locale: zhCn,
    // 支持 large、default、small
    size: Cookies.get("size") || "default",
  });
  app.use(hiPrintPlugin)
  hiPrintPlugin.disAutoConnect();
  const c = container
    ? container.querySelector("#app")
    : document.getElementById("app");

  if (routerEvent) {
    // 如果首次跳转子页面就直接跳到父级页面
    let path = routes.find((item) => item.path === routerEvent.path);
    // 页面路由跳转加上?mustJump=true  可以强制跳转子页面  暂未使用 后续自由扩展
    if (
      path &&
      path.mate &&
      path.meta.parentName &&
      !(routerEvent && routerEvent.query && routerEvent.query.mustJump)
    ) {
      let parent = routes.find(
        (item) => item.name === path["meta"]["parentName"]
      );
      $parentRouter.push(parent.path);
      keepeStore.pushKeepaliveList(parent.name);
      action.setGlobalState({
        changeMicoTabsPath: {
          to: {
            path: parent.path,
            fullPath: parent.path,
            query: {},
          },
          appName: "tms",
          type: "change",
        },
      });
      return;
    } else {
      const newPath =
        routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, "/");
      const newFullPath =
        routerEvent.fullPath && routerEvent.fullPath.replace(/\/[^/]*\//, "/");
      router.push(newFullPath);
      let find = routes.find((item) => item.path === newPath);
      find && keepeStore.pushKeepaliveList(find.name);
    }

    requestAnimationFrame(() => {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: "changeLoading",
          loading: false,
        },
      });
    });
  }
  app.mount(c);
}

renderWithQiankun({
  mount(props) {
    console.log(packageName + ": mount--子应用挂载", props);
    action.setActions(props);
    render(props);
  },
  bootstrap() {
    console.log(packageName + ": bootstrap");
  },
  unmount(props) {
    keepeStore.clearKeepaliveList()
    app.unmount();
    app._container.innerHTML = ''
    app = null
    console.error(packageName + ': unmount--销毁子应用')
  },
  update(props) {
    let { routerEvent } = props;

    if (routerEvent) {
      switch (routerEvent.type) {
        case "push":
          {
            console.log("执行添加");
            const newPath =
              routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, "/");
            const newFullPath =
              routerEvent.fullPath &&
              routerEvent.fullPath.replace(/\/[^/]*\//, "/");
            router.push(newFullPath);
            const path = routes.find((item) => item.path === newPath);
            keepeStore.pushKeepaliveList(path?.name);
          }
          break;
        case "replace":
          {
            console.log("执行替换");
            const newPath =
              routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, "/");
            const newFullPath =
              routerEvent.fullPath &&
              routerEvent.fullPath.replace(/\/[^/]*\//, "/");
            router.replace(newFullPath);
          }
          break;
        case "close":
          {
            console.log("执行关闭");
            const newPath =
              routerEvent.path && routerEvent.path.replace(/\/[^/]*\//, "/");
            keepeStore.closeKeepaliveList(
              routes.find((item) => item.path === newPath)
            );
          }
          break;
        case "visible":
          {
            console.warn("visible");
          }
          break;
      }
    }
  },
});

// 独立运行时
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({});
}
